package com.longway.common.ext.directive;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
import com.longway.common.constant.Const;
import com.longway.common.model.BaseUser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelectDirective extends Directive {

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        BaseUser baseUser = (BaseUser) scope.getRootData().get(Const.loginAccountCacheName);
        //type="dict" code="101" name="sex" value="" tail  required source where
        String[] param = getParaArray(scope);

        String type = param[0];
        final String code = param[1];
        String name = param[2];
        Object value = param[3];
        String tail = "";
        if (param.length >= 5) {
            tail = param[4];
        }
        String required = "";
        if (param.length >= 6) {
            required = param[5];
        }
        String source = "";
        if (param.length >= 7) {
            source = param[6];
        }
        String where = "";
        if (param.length >= 8) {
            where = param[7];
        }
        String sql = "";

        String CACHE_NAME = Const.DICT_CACHE;

        if (type.equals("dict")) {
            sql = "select num as id,pid as pid,name as text from  base_dict where code=" + code + "  and num>=0";
        }
        if (type.equals("hangyeTree")) {
            sql = "select mc as text,id,pid as pId from lhyg_tt_catalogue where pid in(" + code + ")";
        } else if (type.equals("user")) {
            CACHE_NAME = Const.USER_CACHE;
            sql = "select id,name as text from  base_user ";
            if (StrKit.notBlank(where)) {
                where = " where " + where + " and status=2";
            } else {
                where = "where status=2";
            }
            sql = sql + where;
        } else if (type.equals("dept")) {
            CACHE_NAME = Const.DEPT_CACHE;
            sql = "select id,simplename as text from  base_dept";
            if (StrKit.notBlank(where)) {
                where = " where " + where;
            }
            sql = sql + where;
        } else if (type.equals("role")) {
            CACHE_NAME = Const.ROLE_CACHE;
            sql = "select id,name as text from  base_role";
            if (StrKit.notBlank(where)) {
                where = " where " + where;
            }
            sql = sql + where;
        } else if (type.equals("diy")) {
            CACHE_NAME = Const.DIY_CACHE;
            type = type + "_" + source;
            Map<String, String> modelOrMap = new HashMap<String, String>();
            ;
            if (StrKit.notBlank(where)) {
                where = " where " + where;
            } else {
                where = "";
            }
            SqlPara sqlPara = Db.getSqlPara(source, modelOrMap);
            sql = sqlPara.getSql() + where;
        }
        final String _sql = sql;
        List<Record> dict = null;
        //非静态数据
        if (!type.equals("static")) {
            if (StrKit.notBlank(where)) {
                dict = Db.find(_sql);
            } else {
                dict = CacheKit.get(CACHE_NAME, type + "_" + code + "_" + baseUser.getId(), new IDataLoader() {
                    @Override
                    public List<Record> load() {
                        return Db.find(_sql);
                    }
                });
            }
        } else {//静态数据
            if (StrKit.notBlank(source)) {
                dict = new ArrayList<Record>();
                List<JSONObject> dics = JsonKit.parse(source, List.class);
                for (JSONObject dic : dics) {
                    Record re = new Record().set("id", dic.getString("id"))
                            .set("text", dic.getString("text"));
                    dict.add(re);
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        String sid = "_" + name.split("\\.")[1];
        sb.append("<div id=" + sid + "_div>");
        sb.append("<select  onchange=\"" + sid + "_selectChanged('" + sid + "')\" " + required + " class=\"form-control\" id=\"" + sid + "\"  name=\"" + name + "\">");//+ token
        sb.append("<option value></option>");

        for (Record dic : dict) {
            String id = dic.getStr("id");
            String selected = "";
            if (id.equals(value)) {
                selected = "selected";
            }
            sb.append("<option " + selected + " value=\"" + id + "\">" + dic.getStr("text") + "</option>");
        }
        sb.append("</select>");
        sb.append("</div>");

        sb.append("<script type=\"text/javascript\">");
        sb.append(" $(function(){ var stext=$('#" + sid + " option:selected').text();$('#" + sid + "').val('" + value + "'); $('#" + sid + "_ext').val(stext);});");
        sb.append("		function " + sid + "_selectChanged(sid) {");
        sb.append("			$('#form_token').val(1);");
        sb.append("			$('#' + sid).attr('name','" + name + "');");
        if (StrKit.notBlank(tail)) {
            sb.append("			var options=$('#' + sid + ' option:selected');");
            sb.append("			$('#' + sid + '_ext').val(options.text());");
        }
        sb.append("		};");
        sb.append("		function " + name.split("\\.")[1] + "_readonly() {");
        sb.append("		$('#" + sid + "_ext').remove(); var options=$('#" + sid + " option:selected'); var otext = options.text(); var value = $('#" + sid + "').val();");
        sb.append("		$('#" + sid + "_div').empty(); $('#" + sid + "_div').append('<input type=\"text\" style=\"display:none\" id=\"" + sid + "\" name=\"" + name + "\"  /><input type=\"text\" id=\"" + sid + "_ext\" name=\"" + name.split("\\.")[0] + "." + tail + "\" readonly=\"readonly\" class=\"form-control\" />');");
        sb.append("		 $('#" + sid + "').val(value);$('#" + sid + "_ext').val(otext);");
        sb.append("		};");
        sb.append("</script>");
        if (StrKit.notBlank(tail)) {
            sb.append("<input type=\"hidden\" id=\"" + sid + "_ext\" name=\"" + name.split("\\.")[0] + "." + tail + "\">");
        }
        try {
            writer.write(sb.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 从 #select 指令参数中获取type="dict" code="101" name="sex" value="0" tail intercepter
     */
    private String[] getParaArray(Scope scope) {
        Object[] values = exprList.evalExprList(scope);
        String[] ret = new String[values.length];
        if (ret.length == 0) {
            throw new ParseException("#select directive parameter cant not be null", location);
        }
        for (int i = 0; i < values.length; i++) {
            if (values[i] instanceof String) {
                ret[i] = (String) values[i];
            } else {
                ret[i] = String.valueOf(values[i]);
            }
        }
        return ret;
    }

}
